<?php
namespace app\api\controller;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
header("Content-type:text/html;charset=utf-8");
Loader::import('Wxpay.Wxpay.WxPay', EXTEND_PATH, '.Api.php');//将附件放入根目录下的/extend
Loader::import('Wxpay.Wxpay.WxPay', EXTEND_PATH, '.Config.php');//将附件放入根目录下的/extend
class Openid extends Controller
{

    //获取内容
    protected $config;
    public function _initialize()
    {
        $config=new \WxPayConfig();
        $this->config=$config->_config;
    }

    //微信授权登陆
    public function userInfo()
    {
        $openid=input('openid');
        $cha=db('user')->where('code',$openid)->field('uid')->find();
        $uid=$cha['uid'];//openid转uid
        $sex=input('sex');
        if($sex==0)
        {
            $sex='未知';
        }
        if($sex==1)
        {
            $sex='男';
        }
        if($sex==2)
        {
            $sex='女';
        }
        $region=input('diqu');
        $nickname=input('nickname');
        $avatars_img=input('touxiang');
        //表情转码
        /*$strEncode = '';
        $length = mb_strlen($nickname,'utf-8');
        for ($i=0; $i < $length; $i++) {
            $_tmpStr = mb_substr($nickname,$i,1,'utf-8');
            if(strlen($_tmpStr) >= 4){
                $strEncode .= rawurlencode($_tmpStr);
            }else{
                $strEncode .= $_tmpStr;
            }
        }*/
        $xiu=db('user')->where('uid',$uid)->update(['region'=>$region,'nickname'=>$nickname,'head_portrait'=>$avatars_img,'sex'=>$sex]);
     
        if($xiu)
        {
            return $this->AjaxReturn("1", "授权成功！");
        }
        else
        {
            return $this->AjaxReturn("-1", "授权失败！");
        }

    }

    //获取微信登录用户信息
    public function openid()
    {
        $array=array();
        $appid = input('appid');
        $appsecret = input('appsecret');
        $code = input('code');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appsecret&js_code=$code&grant_type=authorization_code";
        $weixin = file_get_contents($url);//通过code换取网页授权access_token
        $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
        //$array = get_object_vars($jsondecode);//转换成数组
        //$aaa=$array($weixin);
        //$openid = $array['openid'];//输出openid
        return $weixin;
    }

    /* 微信支付完成，回调地址url方法  xiao_notify_url() */
    public function xiao_notify_url(){
        $pers=time();
        $xml=file_get_contents("php://input");
        $data = $this->xml_to_array($xml);//微信支付成功，返回回调地址url的数据：XML转数组Array
        $postSign = $data['sign'];
        unset($data['sign']);
        $result = $data;
        ksort($data);// 对数据进行排序

        $str1 = $this->sign($data);//对数组数据拼接成key=value字符串
        $user_sign = strtoupper(md5($str1));   //再次生成签名，与$postSign比较

        $openid = $data['openid'];
        $uid=db('user')->where('code',$openid)->field('uid')->find();
        $total_fee = ($data['total_fee']);
        $where['number'] = $data['out_trade_no'];
        $order_status = db('pay')->where($where)->find();
        if(($data['return_code']=='SUCCESS') && ($data['result_code'] == 'SUCCESS')){
            /*
           * 首先判断，订单号是否匹配成功
           * 其次，订单已经为ok的，直接返回SUCCESS
           * 最后，订单没有为ok的，更新状态为ok，返回SUCCESS
           */
            if($order_status['flg']=='已支付'){
                if ($result) {
                    $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                }else{
                    file_put_contents(ROOT_PATH . '/upload' . DS . 'zhifu' . $pers, $result);
                    $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
                }
                echo $str;
                exit();
            }else {
                db('pay')
                    ->where('number', $order_status['number'])
                    ->update(['flg' => '已支付']);
                if ($order_status) {
                    $taocan = db('real')
                        ->join('f_package', 'f_real.tid=f_package.tid','left')
                        ->where('f_real.uid', $uid['uid'])
                        ->field('f_package.phase_time')
                        ->find();//查询套餐日期
                } else {
                    file_put_contents(ROOT_PATH . '/upload' . DS . 'xiugai' . $pers, $order_status);//
                    $result = false;
                }
            }
        }else {
            file_put_contents(ROOT_PATH.'/upload'.DS.'cuowu'.$pers,$xml);
            $result = false;
        }
        if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
            file_put_contents(ROOT_PATH . '/upload' . DS . 'nosign' . $pers,$result);
        }

        echo $str;
        exit();
        //return $result;
    }
    /* 微信支付完成，回调地址url方法  notify_url() */
    public function notify_url(){
        $pers=time();
        $xml=file_get_contents("php://input");
        $data = $this->xml_to_array($xml);//微信支付成功，返回回调地址url的数据：XML转数组Array
        $postSign = $data['sign'];
        unset($data['sign']);
        $result = $data;
        ksort($data);// 对数据进行排序

        $str1 = $this->sign($data);//对数组数据拼接成key=value字符串
        $user_sign = strtoupper(md5($str1));   //再次生成签名，与$postSign比较

        $openid = $data['openid'];
        $uid=db('user')->where('code',$openid)->field('uid')->find();
        $total_fee = ($data['total_fee']);
        $where['number'] = $data['out_trade_no'];

        $order_zixun=db('zpay')->where($where)->find();
        if(($data['return_code']=='SUCCESS') && ($data['result_code'] == 'SUCCESS')){
            /*
           * 首先判断，订单号是否匹配成功
           * 其次，订单已经为ok的，直接返回SUCCESS
           * 最后，订单没有为ok的，更新状态为ok，返回SUCCESS
           */
            if($order_zixun['flg']=='已支付'){
                if($result) {
                    $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                }else{
                    file_put_contents(ROOT_PATH . '/upload' . DS . 'nozhifu' . $pers, $result);
                }
                echo $str;
                exit();
            }else {
                if ($order_zixun) {
                    db('zpay')
                        ->where('number', $order_zixun['number'])
                        ->update(['flg' => '已支付']);
                } else {
                    file_put_contents(ROOT_PATH . '/upload' . DS . 'noxiugai' . $pers, $order_zixun);
                    $result = false;
                }
            }
        }else {
            file_put_contents(ROOT_PATH.'/upload'.DS.'cuowu'.$pers,$result);
            $result = false;
        }
        if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            file_put_contents(ROOT_PATH . '/upload' . DS . 'nosuccess' . $pers, $result);
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        exit();
        //return $result;
    }
    //签名
    private function sign($data){
        $keys=$this->config['KEY'];
        //步骤一：按字典序排列参数
        ksort($data);
        $buff='';
        foreach ($data as $k=>$v) {
            if($k!="sign"&&$v!=""&&!is_array($v)){
                $buff.=$k."=".$v."&";
            }
        }
        $buff=trim($buff,"&");
        //步骤二：在string后面贾$key
        $string=$buff. "&key=".$keys;
        //步骤三：md5加密
        $string=md5($string);
        //步骤四：所有字符转化为大写
        $sign=strtoupper($string);
        //dump($sign);
        return $sign;
    }

    /*
     * 不知道是啥
     *
     */
    private function xml_to_array($xml){
        //将XML转为array 禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        //simplexml_load_string()解析读取xml数据，然后转成json格式
        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }
    //详细页面的查看
    public function chakan()
    {
        $openid=input('openid');
        $data = Db::name('user')->where('code',$openid)->find();
        $openid=$data['uid'];
        $mid=input('mid');//接收文章mid
        $uid=input('uid');//接收文章发布人地uid

        if(!empty($mid))
        {
            $list = Db::name("message")
                ->alias('me')
                ->where('mid',$mid)
                ->join('f_real re','re.uid=me.uid','left')
                ->join('f_user us','us.uid=re.uid','left')
                ->field('me.mid,me.price,me.number,me.unit,me.address,us.uname,us.nickname,me.createtime,me.picture,me.content,us.company,us.phone,me.num,me.id,us.gflg,me.uid,me.title,re.rflg')->find();//print_r($list);die;
            if($list['gflg']==1)
            {
                $list['nickname']='农厂汇官网';
            }
            elseif($list['uname']=='')
            {
                $list['nickname']=$list['nickname'];
            }
            else
            {
                $list['nickname']=$list['uname'];
            }
            if($list['unit']==1)
            {
                $list['unit']='吨';
            }
            elseif($list['unit']==2)
            {
                $list['unit']='公斤';
            }
            elseif($list['unit']==3)
            {
                $list['unit']='斤';
            }
            else
            {
                $list['unit']='个';
            }
            //判断是不是实名
            if($list['gflg']=='1')
            {
                $list['uname']='农厂汇官网';
            }
            elseif ($list['uname']=='')
            {
                $list['uname']=$list['nickname'];
            }
            else
            {
                $list['uname']=$list['uname'];
            }
            //图片加空
            $url='https://www.mamingwang.cn/upload/message/';
            if($list['picture']!='')
            {
                $img=array_filter(explode(',',$list['picture']));
                foreach ($img as $key=>$value9)
                {
                    $lis[]=$url.$value9;
                }
                //print_r($lis);die;
                $list['picture']=$lis;
            }
            else
            {
                $list['picture']=array($url.'no.jpg');
            }
            //查询是否关注追加到fans字段
            $fen=db('fans')->where('uid',$uid)->find();
            $arr=array_filter(explode(',',$fen['fuid']));
            //return 'uid'.$openid.'kong'.$fen['fuid'];die;
            if(in_array($openid,$arr))
            {
                $list['fans']=1;
                //判断是不是我发表地文章
                if($openid==$uid)
                {
                    $list['fans']=2;
                }
            }
            else
            {
                $list['fans']=0;
                //判断是不是我发表地文章
                if($openid==$uid)
                {
                    $list['fans']=2;
                }
            }
            //查询我又没有点赞这篇文章
            $dian=db('message')->where('mid',$mid)->field('id')->find();
            $arr1=array_filter(explode(',',$dian['id']));
            //return $openid.'->'.$dian['id'];die;
            if(in_array($openid,$arr1))
            {
                $list['dian']=1;
            }
            else
            {
                $list['dian']=0;
            }
            //计算点赞数量
            $num=array();
            $num=array_filter(explode(',',$list['id']));
            $list['id']=count($num);
            //计算评论数量
            $cha=db('evalute')->where('message_id',$mid)->where('bpid',0)->select();
            $list['num2']=count($cha);
            //print_r($num);die;
            //点赞的人
            if($list['id']!=0)
            {
                for($i=0;$i<count($num);$i++)
                {
                    $diannum[]=db('user')->where('uid',$num[$i])->field('uid,uname,nickname')->find();
                    if($diannum[$i]['uname']=='')
                    {
                        $diannum[$i]['uname']=$diannum[$i]['nickname'];
                    }
                }
            }
            else
            {
                //like点赞是不是为空
                $diannum=array();
            }

            //浏览加一
            $cha=db('message')->where('mid',$mid)->field('num')->find();
            $num=$cha['num']+1;
            $jia=db('message')->where('mid',$mid)->update(['num'=>$num]);
            //return $this->AjaxReturn("1","浏览数添加成功！");

            /* $data='';
             foreach ($dian as $value)
             {
                 $data.=$value['uname'].',';
             }
             $data=substr($data,0,strlen($data)-1);*/
            //print_r($data);die;
            //print_r($diannum);die;
            $list['like']=$diannum;//var_dump($list);die;//print_r($list);die;
            //$arrr=array_merge($list,$lis);//数组合并

            $bjid=db('message')->where('mid',$mid)->field('f_message.uid')->find();
            //判断是否认证&是否是官方账号
            $rflg=db('real')->join('f_user us','us.uid=f_real.uid')->where('f_real.uid',$openid)->field('f_real.rflg,us.gflg')->find();
            //查询后台设置的转发次数限制
            $shezhi=db('shezhi')->where('zid',1)->field('userwenzhang,vipwenzhang,userbohao,vipbohao,userzhuanfa,vipzhuanfa')->find();
            $timestart=date("Y-m-d 00:00:00");
            $timeend=date("Y-m-d H:i:s");
            $shu=db('zhuanfa')
                ->where('zfid',$openid)
                ->where('f_zhuanfa.z_createtime','between',[$timestart,$timeend])
                ->count();//今日拨号
          if($data['phone']==''){
        	$list['code'] = -2;
        }
            //官方账号无限制
          $list['myuid'] = $data['uid'];
            if($rflg['gflg']==1)
            {
                $list['shu']=$shu;
                $list['zhuan']=99999;
                return $this->AjaxReturn("1","操作成功",$list);
            }
            else
            {
                if($rflg['rflg']==1)
                {
                    $list['shu']=$shu;
                    $list['zhuan']=$shezhi['vipzhuanfa'];
                    return $this->AjaxReturn("1","操作成功",$list);
                }
                else
                {
                    $list['shu']=$shu;
                    $list['zhuan']=$shezhi['userzhuanfa'];
                    return $this->AjaxReturn("1","操作成功",$list);
                }
            }


        }
        else
        {
            return $this->AjaxReturn("-1","未接收到文章mid");
        }
    }

    //短信验证码的发送
    public function sendTemplateSMS()
    {
        $openid = request()->post('openid');
        if ($openid == null) {
            $this->AjaxReturn(-1, "用户信息错误！");
        }
        else
        {
            $data = Db::name('user')->where('code', $openid)->find();
            if (empty($data)) {
                $res = Db::name('user')->insert([
                    'code' => $openid,
                    'uflg' => 1,
                    'gflg' => 0,
                    "avatars_img" => '',
                    "phone" => '',
                    'uname' => '',
                    "company" => ''
                ]);
            }
        }
        //$to,$datas,$tempId
        //$openid=$this->uid;//openid
        $to=input('phone');
        $a=rand(10000,99999);//5位数字随机生成
        $datas=array($a,'5');
        Cache::set($to,$a,600);//缓存存在10分钟
        //$huan=Cache::get($to);
        //return $a;die;
        $tempId="419959";
        vendor('duanxin.CCPRestSmsSDK');

        //sendTemplateSMS($to,array('5556','5'),"1");//手机号码，替换内容数组，模板ID
        //主帐号,对应开官网发者主账号下的 ACCOUNT SID
        $accountSid= '8a216da8555d110e015571b1f40519a5';
        //主帐号令牌,对应官网开发者主账号下的 AUTH TOKEN
        $accountToken= 'dc82f19888114fe6863a75ac3c476487';
        //应用Id，在官网应用列表中点击应用，对应应用详情中的APP ID
        //在开发调试的时候，可以使用官网自动为您分配的测试Demo的APP ID
        $appId='8a216da8555d110e015571b1f53319ab';
        //请求地址
        //沙盒环境（用于应用开发调试）：sandboxapp.cloopen.com
        //生产环境（用户应用上线使用）：app.cloopen.com
        $serverIP='app.cloopen.com';
        //请求端口，生产环境和沙盒环境一致
        $serverPort='8883';
        //REST版本号，在官网文档REST介绍中获得。
        $softVersion='2013-12-26';
        // 初始化REST SDK
        //global $accountSid,$accountToken,$appId,$serverIP,$serverPort,$softVersion;
        $rest = new \REST($serverIP,$serverPort,$softVersion);
        $rest->setAccount($accountSid,$accountToken);
        $rest->setAppId($appId);

        // 发送模板短信
        echo "Sending TemplateSMS to $to <br/>";
        $result = $rest->sendTemplateSMS($to,$datas,$tempId);
        /*if($result == NULL ) {
            echo "result error!";
            break;
        }*/

        if($result->statusCode!=0) {
            echo "error code :" . $result->statusCode . "<br>";
            echo "error msg :" . $result->statusMsg . "<br>";
            //TODO 添加错误处理逻辑
            return $this->AjaxReturn("-1", "发送失败！");
        }else{
            echo "Sendind TemplateSMS success!<br/>";
            // 获取返回信息
            $smsmessage = $result->TemplateSMS;
            echo "dateCreated:".$smsmessage->dateCreated."<br/>";
            echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";
            //TODO 添加成功处理逻辑
            return $this->AjaxReturn("1", "发送成功！");
        }

    }

    //修改手机号
    public function phone()
    {
        $openid=input('openid');
        $cha=db('user')->where('code',$openid)->field('uid')->find();
        $openid=$cha['uid'];//openid
        $phone=input('phone');//接收的手机号
        $code=input('code');//接收验证码
        if($code=='')
        {
            return $this->AjaxReturn("-1", "你输入的验证码不正确！");
        }
        else
        {
            //return Cache::get($phone);die;
            //return 'uid'.$openid.'手机号'.$phone.'输入的验证码'.$code.'手机发送的验证码'.Cache::get($phone);;die;
            if(Cache::get($phone)!=$code)
            {
                return $this->AjaxReturn("-1", "你输入的验证码不正确！");
            }
            else
            {
                $add=db('user')->where('uid',$openid)->update(['phone'=>$phone]);
                return $this->AjaxReturn("1", "手机号修改成功！");
            }

        }

    }

    //注册的提交
    public function zhu()
    {
        $openid=input('openid');

        $cha=db('user')->where('code',$openid)->field('uid')->find();
        $openid=$cha['uid'];//openid
        $phone=input('phone');//接收的手机号
        $code=input('code');//接收验证码
        $pwd=input('pwd');//密码存库
        //return Cache::get($phone);die;
        //return 'uid'.$openid.'手机号'.$phone.'输入的验证码'.$code.'密码'.$pwd.'手机发送的验证码'.Cache::get($phone);;die;
        if(Cache::get($phone)!=$code)
        {
            return $this->AjaxReturn("-1", "你输入的验证码不正确！");
        }
        else
        {
            $pwd=input('pwd');//密码存库
            $time=date('Y-m-d H:i:s');
            $add=db('user')->where('uid',$openid)->update(['pwd'=>$pwd,'phone'=>$phone,'createtime'=>$time]);
            //默认关注官方账号
            $gflg=db('user')->where('gflg',1)->select();
            $a=array();
            foreach ($gflg as $key=>$value)
            {
                $a[]=$value['uid'];
            }
            //官方账号字符串
            $time=date('Y-m-d H:i:s');
            if($a==array())
            {
                $str='';
            }
            else
            {
                $str=implode(',',$a).',';
                //让所有官方账号添加我为粉丝
                foreach ($a as $fuid)
                {
                    $chuan=db('fans')->where('uid',$fuid)->field('fuid')->find();
                    $str2=$chuan['fuid'].$openid.',';
                    $update2=db('fans')->where('uid',$fuid)->update(['fuid'=>$str2]);
                }
                //关注官方账号生成日志
                foreach ($a as $value2)
                {
                    $ribiao=db('ribiao')->insert(['uid'=>$openid,'bid'=>$value2,'createtime'=>$time]);
                }
            }
            //添加公司表、实名认证表、粉丝表
            //防止重复提交提前判断是否创建成功！
            $com=db('company')->where('uid',$openid)->find();
            if(!$com)
            {
                $company=db('company')->insert(['uid'=>$openid]);
            }
            $rea=db('real')->where('uid',$openid)->find();
            if(!$rea)
            {
                $real=db('real')->insert(['uid'=>$openid]);
            }
            $fan=db('fans')->where('uid',$openid)->find();
            if(!$fan)
            {
                $fuid='';
                $fans=db('fans')->insert(['uid'=>$openid,'fuid'=>$fuid,'guid'=>$str,'createtime'=>$time]);
            }
            return $this->AjaxReturn("1", "注册成功！");
        }

    }

    //详情页评论的显示
    public function pinglun()
    {
        $mid=input('mid');//接收文章mid
        //$uid=input('uid');//接收文章发布人地uid
        if(!empty($mid))
        {
            $ping=$this->evalutelist($mid);
            //print_r($ping[0]['down']);die;
            if(empty($ping))
            {
                $ping='abcd';
            }
            return $this->AjaxReturn("1","操作成功",$ping);
        }
        else
        {
            return $this->AjaxReturn("-1","未接收到文章mid");
        }
    }
    public function evalutelist($message_id)
    {
        //$message_id=input('message_id');
        $evalutelist=Db('evalute')
            ->alias('ev')
            ->join('f_user pj','pj.uid=ev.pjid','left')
            ->join('f_user bp','bp.uid=ev.bpid','left')
            ->where('message_id',$message_id)
            ->where('parent_evalute_id',0)
            //->where('ev.sfig',1)
            ->field('ev.*,pj.uname as pjname,pj.avatars_img as tx,pj.head_portrait as wtx,pj.nickname as pjnickname,bp.uname as bpname,bp.nickname as bpnickname')
            ->select();
        $arr=$evalutelist;
        if(!empty($evalutelist)){
            $ur='https://www.mamingwang.cn/upload/portrait/';
            foreach($evalutelist as $k=>$v){
                //return  $arr[$k]['tx'];
                if($v['tx']!='')
                {
                    $arr[$k]['tx']=$ur.$v['tx'];
                }
                else
                {
                    $arr[$k]['tx']=$v['wtx'];

                }
                if($v['pjname']=='')
                {
                    $arr[$k]['pjname']=$v['pjnickname'];
                }
                else
                {
                    $arr[$k]['pjname']=$v['pjname'];
                }
                $downevalute=Db('evalute')->where('message_id',$message_id)->where('parent_evalute_id',$v['evalute_id'])->count();
                if($downevalute>0){
                    $arr[$k]['down']=$this->getdownevalutes(array(), $message_id, $v['evalute_id']);
                }else{
                    $arr[$k]['down']=array();
                }
            }
        }return $arr;
    }
    public function getdownevalutes($arr,$message_id,$parent_evalute_id)
    {
        $downevalute=Db('evalute')
            ->where('message_id',$message_id)
            ->where('parent_evalute_id',$parent_evalute_id)
            ->count();
        if($downevalute>0) {
            $evalute = Db('evalute')
                ->alias('ev')
                ->join('f_user pj','pj.uid=ev.pjid','left')
                ->join('f_user bp','bp.uid=ev.bpid','left')
                ->where('message_id', $message_id)
                ->where('parent_evalute_id',$parent_evalute_id)
                // ->where('ev.sfig',1)
                ->field('ev.*,pj.uname as pjname,pj.nickname as pjnickname,bp.uname as bpname,bp.nickname as bpnickname')
                ->select();
            foreach ($evalute as $k) {
                if($k['pjname']=='')
                {
                    $k['pjname']=$k['pjnickname'];
                }
                else
                {
                    $k['pjname']=$k['pjname'];
                }
                if($k['bpname']=='')
                {
                    $k['bpname']=$k['bpnickname'];
                }
                else
                {
                    $k['bpname']=$k['bpname'];
                }
                $arr[] = $k;
                $arr = $this->getdownevalutes($arr, $message_id, $k['evalute_id']);
            }
        }
        return $arr;
    }
    public function AjaxReturn($code,$msg,$data=array())
    {

        $returnData=array(
            "code"=>$code
        );
        if($msg)
        {
            $returnData["message"]=$msg;
        }else
        {
            $returnData["message"]=$this->getErrorInfo($code);
        }
        if(!empty($data))
        {
            $returnData["data"]=$data;
        }
        exit(json_encode($returnData));
    }

}